package com.zyf.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zyf.common.excption.YyghException;
import com.zyf.common.result.ResultCodeEnum;
import com.zyf.service.OssService;
import com.zyf.utils.ConstantOSSPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;

/** oss文件上传 业务处理实现类
 * @author zyf
 * @date 2021年05月21日 14:59
 */
@Service
public class OssServiceImpl implements OssService {


    /**
     * 上传文件到阿里云oss
     * @author zyf
     * @date 2021/5/21 15:01
     * @param file 文件流
     * @return java.lang.String
     */
    @Override
    public String upload(MultipartFile file) {
        //设置上传的参数
        String endpoint = ConstantOSSPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantOSSPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOSSPropertiesUtils.SECRET;
        String bucketName = ConstantOSSPropertiesUtils.BUCKET;

        //创建OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        //得到文件流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();

            String fileName = file.getOriginalFilename();


            //生成随机性唯一值，使用uuid，添加到名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            if (fileName.length()<20){
                fileName = uuid + fileName;
            }
            fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8);

            //按照当前日期，创建文件夹，上传到创建的文件夹里
            String timeUrl = new DateTime().toString("yyyy/MM/dd");

            fileName = timeUrl+"/"+fileName;

            //上传文件流
            ossClient.putObject(bucketName,fileName,inputStream);

            //关闭OssClient
            ossClient.shutdown();

            //上传之后文件的路径
           //String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();
            return url;
        } catch (IOException e) {
            throw new YyghException(ResultCodeEnum.FAIL);
        }

    }
}
